Imports System
Imports System.IO
Imports System.Text
Imports System.IO.Compression

''' <summary>
''' Methods to handle compression methods (Compress and Decompress).
''' </summary>
Public Class CompressionUtil

#Region "Private constructor"

	Private Sub New()
		' Can't create instance!
	End Sub

#End Region

#Region "GZip"

	''' <summary>
	''' Compresses the passed string using GZip.
	''' </summary>
	''' <returns>Compressed stream, as a byte array.</returns>
	Public Shared Function GZipCompress(ByVal value As String) As Byte()

		If String.IsNullOrEmpty(value) Then
			Return Nothing
		End If

		Return GZipCompress(Encoding.UTF8.GetBytes(value))

	End Function

	''' <summary>
	''' Compresses the passed byte array using GZip.
	''' </summary>
	''' <returns>Compressed stream, as a byte array.</returns>
	Public Shared Function GZipCompress(ByVal value() As Byte) As Byte()

		If value.Length < 1 Then
			Return Nothing
		End If

		Dim ms As New MemoryStream()
		Dim zip As New GZipStream(ms, CompressionMode.Compress, True)

		zip.Write(value, 0, value.Length)
		zip.Close()
		ms.Position = 0

		Dim compressed(Convert.ToInt32(ms.Length)) As Byte
		ms.Read(compressed, 0, compressed.Length)

		Dim gzBuffer(compressed.Length + 4) As Byte

		Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length)
		Buffer.BlockCopy(BitConverter.GetBytes(value.Length), 0, gzBuffer, 0, 4)

		ms.Dispose()

		Return gzBuffer

	End Function

	''' <summary>
	''' Decompresses the passed byte array using GZip.
	''' </summary>
	''' <returns>Decompressed stream, as a byte array.</returns>
	Public Shared Function GZipDecompress(ByVal compressed() As Byte) As Byte()

		If compressed.Length < 1 Then
			Return Nothing
		End If

		Try

		Catch ex As Exception

		End Try

		Using ms As New MemoryStream

			Dim msgLength As Int32 = BitConverter.ToInt32(compressed, 0)
			Dim decBuffer(msgLength) As Byte

			ms.Write(compressed, 4, compressed.Length - 4)
			ms.Position = 0

			Dim zip As New GZipStream(ms, CompressionMode.Decompress)
			zip.Read(decBuffer, 0, decBuffer.Length)

			Return decBuffer

		End Using
		
	End Function

#End Region

End Class